package com.gameloops;

public class Gameloop1 extends Thread {
	private final long updateTime = 1000000000 / 58; //Time in nanoseconds
	
	private boolean gameIsRunning = false;
	private long lastUpdateTime;
	private float updateFactor;
	
	@Override
	public void run(){
		lastUpdateTime = System.nanoTime();
		gameIsRunning = true;
		while(gameIsRunning){
			long now = System.nanoTime();
			long updateLength = now - lastUpdateTime;
			lastUpdateTime = now;

			//Update game here
			updateFactor = (float)updateLength/1000000000;
			System.out.println("FPS: " + 1f / updateFactor);

			try {
				//long sleepTime = (lastUpdateTime-System.nanoTime() + updateTime)/1000000;
				//long calculationsDuration = System.nanoTime() - lastUpdateTime; //nanoseconds
				
				long sleepTime = (lastUpdateTime-System.nanoTime() + updateTime)/1000000;
				//If sleepTime is smaller than 0, then the maximum of 60 FPS is not reached
				//so there is no need for restriction the FPS amount to 60 by sleeping.
				if(sleepTime > 0)
					Thread.sleep(sleepTime);
			} catch (InterruptedException e) {System.out.println("An error occured while updating. Could not sleep.");}
		}
	}
}
